import javax.print.DocFlavor;
import java.util.*;

public class Test {
    public static void main(String[] args) {
        int[] arr  = {1,3,5,7,2,4,6,8};
        int[] ret = smallestK(arr,4);
        for (int x: ret) {
            System.out.print(x);
        }
    }
    static class Compare implements Comparator<Integer>{

        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    }
    public static int[] smallestK(int[] arr, int k) {
        int[] ret = new int[k];
        if(arr == null || k == 0){
            return  ret;
        }
        Compare compare = new Compare();
        Queue<Integer> priorityQueue = new PriorityQueue(k,compare);
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
            int val  = priorityQueue.peek();
            if( val > arr[i]){
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < k; i++) {
            stack.push(priorityQueue.poll());
        }
        for (int i = 0; i < k; i++) {
            ret[i] = stack.pop();
        }
        return ret;
    }
}
